package consumer;

import helpers.CrawlerOloHelper;
import helpers.SolrHelper;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.jms.TextMessage;

import debug.RealEstateDebug;

import model.RealEstate;

import service.ActiveMQService;

public class ContentConsumer implements ServletContextListener,
		MessageListener, ExceptionListener {

	@Override
	public void onException(JMSException arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}

	@Override
	public void onMessage(Message message) {						
		try {
			TextMessage textMessage = (TextMessage) message;
			String url = textMessage.getText();
			if(!url.equals("")){
				if(url.contains("olo.vn")){
					System.out.println("From queue : " + url);
					RealEstate re = CrawlerOloHelper.getContent(url);
					SolrHelper.add(re);
					RealEstateDebug.debug(re);
				}
			}
			
		} catch (Exception e) {			
			e.printStackTrace();
		}		
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		throw new UnsupportedOperationException("Not supported yet.");

	}
	
	public void getMessage() throws JMSException,
			InterruptedException {		
		ActiveMQService.start("contentSMS");
		MessageConsumer consumer = ActiveMQService.session.createConsumer(ActiveMQService.destination);
		ActiveMQService.connection.setExceptionListener(this);
		consumer.setMessageListener(this);
	}			
		
}
